<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace plugins\qbt_order\controller;
//Demo插件英文名，改成你的插件英文就行了
use cmf\controller\PluginBaseController;
use think\Db;
use plugins\qbt_order\service\OrderService;
use think\Validate;
use \think\Request;
use think\Config;
use cmf\phpqrcode\QRcode;
use plugins\qbt_payment_management\controller\PayService;

class IndexController extends PluginBaseController
{
	public function _initialize()
    {
        $this->config = Config::get('database');
    }	

    public function index()
    {
        echo 'Hello,World!';
    }

/*    public function addAddress()
    {
        $address_id = $this->request->param('address_id');
        $type       = $this->request->param('type');
        $consignee  = $this->request->param('consignee');
        $type       = $this->request->param('type');

        $address_info['province_name'] = '请选择省份';
        $address_info['city_name']     = '请选择市区';
        $address_info['district_name'] = '请选择县';
        $address_info['consignee']     = $consignee;
        $this->assign('address_info',$address_info);
          
        $this->assign('type',$type);
        return $this->fetch(":addAddress");
    }    */


    /**
     * 创建一个订单
     */
    public function createOrder()
    {
    	$cart_id      = $this->request->param('cart_id'); // 购物车ID
    	$cart_num_str = $this->request->param('cart_num_str'); // 购物车商品数量(用逗号分割的字符串)
    	$address_id   = $this->request->param('address_id', '', 'intval'); // 收货地址 ID
    	$user_id      = $this->request->param('user_id', '', 'intval'); // 用户ID
        $cart_num     = explode(',', $cart_num_str);
        !$cart_id && $this->error('请输入购物车ID');
        !$cart_num_str && $this->error('请输入购物车商品数量');
        !$address_id && $this->error('请输入收货地址 ID');
        !$user_id && $this->error('请输入用户ID');
		// 创建一个新的订单
		$res = OrderService::createOrder($cart_id,$cart_num_str,$address_id,$user_id);
		if($res['code'] == 0) {
            $order_id = $res['data']['order_id'];
			$order_sn = date('YmdHis').$order_id; // 准备订单号。
            $count = $res['data']['count'];
            $goods = $res['data']['goods'];
			// 修改订单号
			Db::name('order_info')->where('order_id', $order_id)->update(['order_sn' => $order_sn]);
			for( $i=0; $i<$count; $i++ ){
				// 准备订单商品数据
				$order_goods_data = [
					'order_id' => $order_id,
					'goods_id' => $goods[$i]['goods_id'],
					'goods_name' => $goods[$i]['goods_name'],
					'goods_sn' => $goods[$i]['goods_sn'],
					'goods_number' => $cart_num[$i],
					'market_price' => $goods[$i]['market_price'],
					'goods_price' => $goods[$i]['shop_price'],
					'is_real' => $goods[$i]['is_real'],
				];
				//插入订单商品表
				$res = DB::name('order_goods')->insert($order_goods_data);
			}

			$pay = new PayService();
	        $pay_type = 'WxPayController';
            $data['openid'] = $res['data']['openid'];
            $data['order'] = $order_id;
            $data['money'] = 0.01;
            $data['body'] = '测试';
            $data['url'] = 'http://'.$_SERVER['SERVER_NAME'].cmf_plugin_url("QbtOrder://Index/notify");
            $paytype = 'WxPayController';
        	$json = $pay->pay($paytype,$data);
			$this->assign("jsApiParameters", $json);
        	$this->assign("money", 0.01);
	        return $this->fetch(':jspay');
		}
		
    }
    
    /**
     * 执行微信支付后的回调
     */
    public function notify()
    {
        $xml = file_get_contents('php://input'); //获取微信发来的XML信息
		$xmlObj = simplexml_load_string($xml,'SimpleXMLElement',LIBXML_NOCDATA);
        $xmlArr = json_decode(json_encode($xmlObj),true);
        $transaction_id =  $xmlArr['transaction_id'];        
        if($xmlArr['result_code'] == 'SUCCESS'){
            //修改订单状态
            $data["pay_time"] = time();
            $data["pay_status"] = 2;
            $data["order_status"] = 1; 
            Db::name('order_info')->where('order_id', $xmlArr["out_trade_no"])->update($data);
            $this->orderquery($transaction_id);
        }
    }


    /**
     * 订单确认页面
     */
    public function firmOrder()
    {
		$cart_id = $this->request->param('cart_id'); // 购物车id
		$user_id = $this->request->param('user_id');//用户ID
		$cart_num_str = $this->request->param('cart_num'); // 购物车经过用户修改后的商品数量
		$cart_num = explode(',', $cart_num_str);
		$count_cat_id = count($cart_id);

		$sql = "SELECT c.cart_id,g.goods_img as goods_image,g.goods_id,g.goods_name,g.goods_sn,g.shop_price as goods_price, c.store_name FROM {$this->config["prefix"]}cart c RIGHT JOIN {$this->config["prefix"]}goods g ON c.goods_id = g.goods_id WHERE c.cart_id IN ({$cart_id}) AND c.buyer_id = {$user_id} ORDER BY FIELD(c.cart_id,{$cart_id})";

		$goods = Db::query($sql);  // 获取商品信息
		!$goods && $this->error('参数错误');
		$count = count($cart_num);
		$total = '';
		for( $i=0; $i<$count; $i++ ){
			// 获取商品总价格，价格乘以100，防止出现浮点数精度损耗
			$total += $goods[$i]['goods_price'] * 100  * $cart_num[$i]; 
			$goods[$i]['goods_number'] = $cart_num[$i];
		}

		$total /= 100; //处理商品价格，回归正常值

		// 获取收货地址信息
        $consignee = DB::name('address')->where(['member_id' => $user_id,'is_default' => 1])->find();
        // 获取配送方式列表
		$shipping_list = DB::name('shipping')->select();
		$this->assign('goods',$goods);
		$this->assign('cart_num_str',$cart_num_str);
		$this->assign('cart_id',$cart_id);
		$this->assign('shipping_list',$shipping_list);
		$this->assign('total',$total);
        $this->assign('user_id',$user_id);
		$this->assign('consignee',$consignee);
		return $this->fetch(":firmOrder");
    }

	//$url  接口url string
	//$data  附带的参数 array
    function curl($url,$data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * 微信支付成功后前端的跳转界面
     */
	public function pay_success(){
        echo '支付成功';
    }    

	/** 查询支付状态
     * @param $transaction_id 微信支付订单号
     * @return bool
     * @throws \WxPayException
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function orderquery($transaction_id){
        $input = new \WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $config = new \WxPayConfig();
        $result = \WxPayApi::orderQuery($config, $input);
        //添加支付日志
        if(array_key_exists("return_code", $result) && $result["return_code"] == "SUCCESS")
        {
            //添加支付日志
            $data['money'] = $result["total_fee"]/100;
            $data['pay_time'] = strtotime($result["time_end"]);
            $data['pay_type'] = 1;
            $data['transaction_id'] = $result["transaction_id"]; //微信支付单号
            $data['order_no'] = $result["out_trade_no"]; //商户订单号
            $data['trade_type'] = $result["trade_type"]; //交易类型

            DB::table('qbtcmf_payment_log')->insert($data);

            //修改订单状态

            //通知微信服务器
            echo exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
        }
        return false;
    }    
}
